"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  baseURL: process.env.VUE_APP_BASE_API
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response.data;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};
// 创建 axios 实例
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 5000, // 请求超时时间
})

// 请求拦截器
request.interceptors.request.use(
    config => {
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username'); // 从 localStorage 获取 username
      const userid = localStorage.getItem('userid');     // 从 localStorage 获取 userid

      if (token) {
        config.headers['Authorization'] = 'Bearer ' + token
      }

      // **新增或修改这部分代码：发送自定义请求头**
      if (username) {
        config.headers['X-Username'] = username;
      }
      if (userid) {
        config.headers['X-User-Id'] = userid; // 确保 userid 是字符串类型
      }

      return config
    },
    error => {
      console.log(error)
      return Promise.reject(error)
    }
)
Vue.use(Plugin)

export default Plugin;
export {_axios as request}